﻿using S7.Net;
using System;
using System.Drawing;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace MyInvokeDemo0
{
    public partial class Form1 : Form
    {
        Plc plc;
        TaskFactory taskFactory;

        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, System.EventArgs e)
        {
            plc = new Plc(CpuType.S71500, "192.168.0.1", 0, 1);
            taskFactory = new TaskFactory();
            Task task = taskFactory.StartNew(() =>
            {
                while (true)
                {
                    try
                    {
                        if (!plc.IsConnected)
                        {
                            SetStatus("通讯异常", Color.Red);
                            plc.Open();
                        }
                        if (plc.IsConnected)
                        {
                            SetStatus("通讯正常", Color.Green);
                            float val = (float)plc.Read(DataType.DataBlock, 1, 0, VarType.Real, 1);
                            Console.WriteLine(val);
                        }
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine($"出现异常了：{ex.Message}");
                    }
                    Console.WriteLine($"{System.DateTime.Now} 线程 {Thread.CurrentThread.ManagedThreadId} 正在运行");
                    Thread.Sleep(1000);
                }
            });
        }

        private void Form1_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (plc != null)
            {
                plc.Close();
            }
        }

        private void SetStatus(string txt, Color color)
        {
            this.Invoke(new Action(() =>
            {
                toolStripStatusLabel1.Text = txt;
                toolStripStatusLabel1.BackColor = color;
            }));
        }
    }
}
